<template>
  <div class="profile-page">
    <h1>修改个人信息</h1>
    <el-form
        :model="form"
        :rules="rules"
        label-width="80px"
        ref="formRef"
    >
      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="form.nickname" placeholder="请输入新的昵称" />
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" placeholder="请输入邮箱" />
      </el-form-item>

      <el-form-item label="修改密码">
        <el-button type="primary" @click="outerVisible = true">修改密码</el-button>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="updateProfile">保存修改</el-button>
        <el-button @click="goBack">返回</el-button>
      </el-form-item>
    </el-form>

    <!-- 第一步：外部弹窗，放验证密码组件 -->
    <el-dialog v-model="outerVisible" title="验证原始密码">
      <VerifyPasswordDialog :saved-password="savedPassword" @verified="handleVerified" />

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="outerVisible = false">取消</el-button>
          <el-button type="primary" @click="submitVerify">验证</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 第二步：验证成功后，显示修改密码弹窗 -->
    <ChangePasswordDialog
        v-model="showChangePwdDialog"
        @changed="handlePasswordChanged"
    />
  </div>
</template>

<script setup>
import {ref, reactive} from 'vue'
import {ElMessage} from 'element-plus'
import {useRouter} from 'vue-router'

import VerifyPasswordDialog from '@/components/user/VerifyPasswordDialog.vue'
import ChangePasswordDialog from '@/components/user/ChangePasswordDialog.vue'
import { editInfoSelective } from '@/api/user'  // 你的修改用户api

const router = useRouter()
const outerVisible = ref(false)
const showChangePwdDialog = ref(false)

const formRef = ref(null)
const form = reactive({
  id: localStorage.getItem('userId'), // 先从本地拿用户id
  nickname: localStorage.getItem('bio') || '',
  email: localStorage.getItem('email') || '',
  username: localStorage.getItem('username') || '',
})

const rules = {
  nickname: [
    {required: true, message: '请输入昵称', trigger: 'blur'},
    {min: 2, max: 20, message: '长度在 2~20 之间', trigger: 'blur'}
  ],
  email: [
    {required: true, message: '请输入邮箱', trigger: 'blur'},
    {type: 'email', message: '请输入正确的邮箱', trigger: 'blur'}
  ]
}

const savedPassword = localStorage.getItem('password') || ''

const handleVerified = () => {
  outerVisible.value = false
  showChangePwdDialog.value = true
}

const handlePasswordChanged = (newPwd) => {
  localStorage.setItem('password', newPwd)
  ElMessage.success('密码已修改！')
}

// 修改用户信息，并先校验token
const updateProfile = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.warning('请检查输入项')
      return
    }

    const token = localStorage.getItem('token')  // 取token
    if (!token) {
      ElMessage.error('请先登录')
      router.push('/login')
      return
    }

    try {
      console.log(token)
      // 调用修改接口，传token
      await editInfoSelective(form, token)
      console.log(form)
      // 更新本地缓存
      localStorage.setItem('nickname', form.nickname)
      localStorage.setItem('email', form.email)

      ElMessage.success('个人信息已更新！')
      router.back()
    } catch (error) {
      ElMessage.error(error.response?.data || '修改失败')
    }
  })
}

function submitVerify(){
  // 调用验证密码组件内的方法或事件
  // 你这里写具体密码校验逻辑即可
}

const goBack = () => {
  router.back()
}
</script>


<style scoped>
.profile-page {
  max-width: 600px;
  margin: 40px auto;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
</style>
